package cn.larry.tools.easypay.utils;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Larry
 * 2021/8/30 17:45
 *
 * @Version 1.0
 */
@Slf4j
public class WeixinUtil {

    public static JSONObject addMaterial(File file, String type, String title, String introduction, String url) {
        if (file == null)
            return null;

        FileInputStream fileInputStream = null;
        String result = null;
        OutputStream output = null;
        InputStream resp = null;
        try {
            URL uploadURL = new URL(url);

            HttpURLConnection conn = (HttpURLConnection) uploadURL.openConnection();
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(30000);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Cache-Control", "no-cache");
            String boundary = "-----------------------------" + System.currentTimeMillis();
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

            output = conn.getOutputStream();
            output.write(("--" + boundary + "\r\n").getBytes());
            output.write(String.format("Content-Disposition: form-data; name=\"media\"; filename=\"%s\"\r\n", file.getName()).getBytes());
            output.write("Content-Type: video/mp4 \r\n\r\n".getBytes());

            byte[] data = new byte[1024];
            int len = 0;
            fileInputStream = new FileInputStream(file);
            while ((len = fileInputStream.read(data)) > -1) {
                output.write(data, 0, len);
            }

            /*对类型为video的素材进行特殊处理*/
            if ("video".equals(type)) {
                output.write(("--" + boundary + "\r\n").getBytes());
                output.write("Content-Disposition: form-data; name=\"description\";\r\n\r\n".getBytes());
                output.write(String.format("{\"title\":\"%s\", \"introduction\":\"%s\"}", title, introduction).getBytes());
            }

            output.write(("\r\n--" + boundary + "--\r\n\r\n").getBytes());
            output.flush();

            resp = conn.getInputStream();

            StringBuffer sb = new StringBuffer();

            while ((len = resp.read(data)) > -1)
                sb.append(new String(data, 0, len, "utf-8"));
            resp.close();
            result = sb.toString();
        } catch (IOException e) {
            //....
        } finally {
            try {
                if (output != null)
                    output.close();
            } catch (Exception e) {
            }
            try {
                if (fileInputStream != null)
                    fileInputStream.close();
            } catch (Exception e) {
            }
            try {
                if (resp != null)
                    resp.close();
            } catch (Exception e) {
            }
        }
        log.info("微信素材上传应答：\n{}", result);
        return JSONObject.parseObject(result);

    }
}
